All Products
(Total 76 Products)
if (res && res.code === 0 && res.log_id) {
visitLogId = res.log_id;
}
}, 'json');
let pageEnterTime = Date.now(); // 当前“本次活跃区间”的开始时间
let staySeconds = 0; // 已累计的停留秒数
const endVisitUrl = '/Staticip/endVisit';
// 累加当前这次“可见区间”的时间,然后重置起点
function accumulateStayTime() {
const now = Date.now();
const diff = Math.max(0, Math.round((now - pageEnterTime) / 1000));
if (diff > 0) {
staySeconds += diff;
}
pageEnterTime = now; // 重置为当前时间,避免重复计算
}
function reportEndVisit() {
// 退出前先把最后一段可见时间累计进去
accumulateStayTime();
if (staySeconds <= 0) return;
const current_url = window.location.href;
// 构造数据
const formData = new FormData();
formData.append('duration', staySeconds);
formData.append('current_url', current_url);
if (visitLogId > 0) {
formData.append('log_id', visitLogId);
}
// 优先使用 sendBeacon (支持率极高,且不会阻塞页面关闭)
if (navigator.sendBeacon) {
navigator.sendBeacon(endVisitUrl, formData);
} else if (window.fetch) {
// 降级使用 fetch + keepalive
fetch(endVisitUrl, {
method: 'POST',
body: formData,
keepalive: true
}).catch(() => { });
}
}
// 心跳机制:每10秒上报一次当前总时长(防止崩溃丢失数据)
setInterval(function () {
// 只有在页面可见且已有 log_id 时才上报
if (document.visibilityState === 'visible' && visitLogId > 0) {
accumulateStayTime(); // 更新 staySeconds
if (staySeconds > 0) {
$.post(endVisitUrl, {
log_id: visitLogId,
duration: staySeconds,
current_url: window.location.href
});
}
}
}, 10000);
window.addEventListener('beforeunload', reportEndVisit);
// 增加 pagehide 事件,增强移动端(尤其是 iOS Safari)的关闭检测能力
window.addEventListener('pagehide', reportEndVisit);
document.addEventListener('visibilitychange', function () {
const state = document.visibilityState;
if (state === 'hidden') {
// 从可见 -> 隐藏:上报当前累计时间(防止后续被杀后台无法上报)
reportEndVisit();
} else if (state === 'visible') {
// 从隐藏 -> 可见:重新开始一段新的可见区间
pageEnterTime = Date.now();
}
});
$(function () {
$(".code-wrapper").on("click", function () {
$(this).find(".code-box").toggleClass("show");
});
$(".code-wrapper").on("mouseleave", function () {
$(this).find(".code-box").removeClass("show");
});
})
Choose another language
×